#!/usr/bin/python3
# -*- coding: utf-8 -*-
#======================================#
# @Author   : duanqizhong
# @time     : 2022-8-16 11:20
# @file     : generate_conf.py
# @Software : PyCharm
#======================================#
import argparse
import os
import sys
from base.cls import Mysql
from settings import DB_ENV,BASE_DIR
from base.logger import log


business_conf=os.path.join(BASE_DIR,"conf/business_db.ini")

def start():
    point_dbs = get_point_db()
    if not point_dbs:
        return
    write_file(point_dbs)


def get_point_db():
    sql = """select business.id,business.en_name,business_db.db_name,business.im,business.token from business left join business_db on business.id=business_db.business_id"""
    op=Mysql(DB_ENV)
    op.connect(DB_ENV["database"])
    infos=op.fetchall(sql)
    op.close()
    business_dbs = {}
    if infos is None or not infos:
        log.warn("未查询到端和库的对应关系")
        return business_dbs
    for info in infos:
        en_name=info.get("en_name")
        if en_name not in business_dbs.keys():
            business_dbs[en_name] = {}
            business_dbs[en_name]["dbs"] = []
            business_dbs[en_name]["im"] = info.get("im")
            business_dbs[en_name]["token"] = info.get("token")
            business_dbs[en_name]["id"] = info.get("id")
        if info.get("db_name") is not None:
            business_dbs[en_name]["dbs"].append(info.get("db_name"))
    return business_dbs


def write_file(business_dbs):
    with open(business_conf, 'w') as fw:
        for key, value in business_dbs.items():
            fw.write(f"[{key}]\n")
            fw.write(f"id={value['id']}\n")
            fw.write(f"dbs={';'.join(value['dbs'])}\n")
            fw.write(f"im={value['im']}\n")
            fw.write(f"token={value['token']}\n\n\n")


def args_run():
    parse = argparse.ArgumentParser(description="from env_db collect business db info!")
    parse.add_argument("is_bool", type=bool, default="False")
    args = parse.parse_args()
    if args.is_bool:
        start()

def run(is_bool=False):
    if is_bool:
        start()


if __name__ == "__main__":
    if sys.platform.startswith("win"):
        run(True)
    else:
        args_run()